
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>websocket</title>
</head>

<body>
    <div>
        <input type="text" id='name'>
        <button id='send'> 发送</button>
        <div id='content' style="width: 500px;">
            
        </div>
    </div>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
// var socket = new WebSocket('ws://121.248.49.232:9000');
var url = "ws://10.1.1.128:9000";
//兼容 FireFox
if ("WebSocket" in window) {
    socket = new WebSocket(url);
} else if ("MozWebSocket" in window) {
    socket = new MozWebSocket(url);
}
socket.onopen = function(event) {
    socket.send("已连接~");
};
socket.onmessage = function(event) {//当客户端收到服务端发来的消息时，会触发onmessage事件，参数event.data中包含server传输过来的数据
    var content = event.data;//获取消息
    console.log(content);
    var html = document.getElementById("content").innerHTML;
    document.getElementById("content").innerHTML = html + "//" + content;
};
socket.onclose = function(evt)
{
  console.log("WebSocketClosed!");
};
socket.onerror = function(evt)
{
  console.log("WebSocketError!");
};

var send = document.getElementById('send');
var secs = 10; 

send.addEventListener('click', function() {
    var value = document.getElementById("name").value;
    socket.send(value);
    document.getElementById("name").value = '';
    timer(1);
});

document.onkeydown=()=>{
    var currKey=0,e=e||event;
     if(e.keyCode==13)
     {
        var value = document.getElementById("name").value;
        socket.send(value);
        document.getElementById("name").value = '';
        timer(1);
     }
};

function timer(time) {
    var btn = $("#send");
    btn.attr("disabled", true);  //按钮禁止点击
    btn.val(time <= 0 ? "发送动态密码" : ("" + (time) + "秒后可发送"));
    var hander = setInterval(function() {
        if (time <= 0) {
            clearInterval(hander); //清除倒计时
            btn.val("发送动态密码");
            btn.attr("disabled", false);
            return false;
        }else {
            btn.val("" + (time--) + "秒后可发送");
        }
    }, 1000);
}


</script>
</html>